﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Security;
using System.Security.Cryptography;
using System.Text;
using System.Configuration;
using System.Web.Configuration;
using System.Net.Configuration;
using System.Net.Mail;
using System.IO;


public partial class ThanhToan : System.Web.UI.Page
{
    public long tong_tien;
    public static String FormAddress
    {
        get
        {
            SmtpSection cfg = (SmtpSection)ConfigurationManager.GetSection
                ("system.net/mailSettings/smtp");
            return cfg.Network.UserName;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        
        ShoppingCart Cart = (ShoppingCart)Session["gio_hang"];
        if (Cart != null)
            tong_tien = Cart.Total;
        DataTable tem = Cart;
        ListView1.DataSource = tem;

        //Label tem = (Label)ListView1.Items[].FindControl("tong_tien");

        if (!IsPostBack)
        {
            ListView1.Items.Clear();
            ListView1.DataBind();
            //this.FillShoppingCart();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
     //   define_smtp();
        string diachi = DiaChi.Text;
        string sodt = SoDienThoai.Text;
        string email = Email.Text;

        string data="";
        Random rand = new Random();
        int curtime = DateTime.Now.Millisecond;
        data = rand.Next(1000000,9999999).ToString() + curtime.ToString();

        string code = cal_code(data).Substring(0,8);

        DateTime cur = DateTime.Now;
        
        SqlDataSource1.InsertCommand = "INSERT INTO [DonDatHang] ([code], [IDUser],  " 
  + "  [ThoiDiemLapDDH], [TongTien], [SoDienThoaiNguoiNhan], [DiaChiGiaoHang],"
  + "[EmailNguoiNhan], [TrangThai]) VALUES ('" + code +"', '"+ "1" +"','" + cur
  + " ','" + tong_tien +"','" + sodt+ "', '"+ diachi +"', '" + email +"', '0' ); ";

        int kq = SqlDataSource1.Insert();

        SqlDataSource1.SelectCommand = "SELECT MAX(IDDonDatHang) FROM DonDatHang;";
        DataView dv= (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
        int ID = (int)dv.Table.Rows[0][0];

        ShoppingCart cart = (ShoppingCart)Session["gio_hang"];
        for (int i = 0; i < cart.Rows.Count; i++)
        {
            DataRow row =  cart.Rows[i];
            int ma = (int)row["IDTaiLieu"];
            string ten = (string)row["TenTL"];
            int DonGia = (int)row["DonGia"];
            int SoLuong = (int)row["SoLuong"];

            SqlDataSource1.InsertCommand = "INSERT INTO [ChiTietDDH] ([IDDonDatHang], [IDTaiLieu],  "
  + "  [TenTL], [SoLuong], [DonGia]) VALUES ('" + ID + "', '" +  ma
  + " ','" + ten + "','" + SoLuong + "', '" + DonGia + "'); ";

            SqlDataSource1.Insert();

        }
     //send mail
        StreamReader sr = new StreamReader(Server.MapPath("~/mail.html"));
        sr = File.OpenText(Server.MapPath("~/mail.html"));
        string content = sr.ReadToEnd();
        content = content.Replace("[Sender]", "AdminNhacungcap");
        content = content.Replace("[Email]", "saitamcai123@gmail.com");
        content = content.Replace("[Content]", "Cám ơn quý khách đã đặt hàng. Mã code của đơn hàng là : " + code);
        content = content.Replace("[DateTime]", DateTime.Now.ToShortDateString());
        try
        {
            Response.Write(SendMail("Liên hệ khách hàng", content, Email.Text, true, true));
            Result.Text = "Cám ơn quý khách đã đặt hàng. Mã code của đơn hàng là : " + code;
            Result.Visible = true;
        }
        catch (Exception ex)
        {
            Result.Text = "Lỗi. Dữ liệu không hợp lệ";
            Result.Visible = true;
            Response.Write(ex.Message);
        }


        cart = null;
        Session["gio_hang"] = cart;
        ListView1.Visible = false;
        ASP.masterpage_master master = (ASP.masterpage_master)this.Master;
        master.RefreshShoppingCartInfo();
    }
    protected string cal_code(string input)
    {

        // step 1, calculate MD5 hash from input
        MD5 md5 = System.Security.Cryptography.MD5.Create();
        byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
        byte[] hash = md5.ComputeHash(inputBytes);
     
        // step 2, convert byte array to hex string
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hash.Length; i++)
        {
            sb.Append(hash[i].ToString("X2"));
        }
        return sb.ToString();

    }
    protected void define_smtp()
    {
        Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration("/web.config");

        MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;

        if (mailSettings != null)
        {
            mailSettings.Smtp.Network.Port = 587;
            mailSettings.Smtp.Network.Host = "smtp.gmail.com";
            mailSettings.Smtp.Network.Password = "saitamcai";
            mailSettings.Smtp.Network.UserName = "saitamcai123";
        }
    }

    public string format_tt(string tt)
    {

        string rs = tt;
        //thay dau ',' thanh '.'
        int l = (rs.Length - 1) / 3;
        for (int i = 0; i < l; i++)
        {
            rs = rs.Insert(rs.Length - (i + 1) * 3 - i, ".");
        }

        return rs;
    }

    public string SendMail(string subject, string body, string to, bool isHtml, bool isSSL)
    {
        try
        {
            using (MailMessage mail = new MailMessage())
            {

                mail.From = new MailAddress(FormAddress);
                mail.To.Add(to);
                mail.Subject = subject;
                mail.Body = body;
                mail.IsBodyHtml = isHtml;
                SmtpClient client = new SmtpClient();
                client.EnableSsl = isSSL;
                client.Send(mail);

            }

        }
        catch (SmtpException ex)
        {
            return ex.Message;
        }
        return "Send email successful!";

    }
}
